<template>
  <div class="students-container">
    <el-card class="students-card">
      <div slot="header">
        <span>学生管理</span>
      </div>

      <!-- 班级信息缺失提示 -->
      <div v-if="noClassInfo" class="no-class-info">
        <el-alert
          title="未设置带班信息"
          type="warning"
          description="您还未设置带班信息，请先在个人中心设置带班年级和班级，才能查看和管理学生。"
          show-icon
          :closable="false">
          <template slot="title">
            未设置带班信息
            <el-button 
              type="text" 
              @click="$router.push('/teacher/profile')"
              style="margin-left: 10px">
              去设置
            </el-button>
          </template>
        </el-alert>
      </div>

      <!-- 当有班级信息时显示学生管理界面 -->
      <template v-else>
        <!-- 带班信息显示 -->
        <div class="class-info">
          <el-alert
            type="info"
            :closable="false">
            <template slot="title">
              当前带班信息：{{ teacherInfo.grade }}级{{ teacherInfo.classId }}班
            </template>
          </el-alert>
        </div>

        <!-- 搜索和过滤 -->
        <div class="filter-container">
          <el-form :inline="true" :model="filterForm" class="filter-form">
            <el-form-item label="用户号">
              <el-input
                v-model="filterForm.userId"
                placeholder="请输入用户号"
                clearable
                @clear="handleSearch">
              </el-input>
            </el-form-item>
            <el-form-item label="姓名">
              <el-input
                v-model="filterForm.name"
                placeholder="请输入姓名"
                clearable
                @clear="handleSearch">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 学生列表 -->
        <el-table
          v-loading="loading"
          :data="students"
          style="width: 100%">
          <el-table-column
            prop="userId"
            label="用户号"
            width="120">
          </el-table-column>

          <el-table-column
            prop="name"
            label="姓名"
            width="120">
          </el-table-column>

          <el-table-column
            prop="universityName"
            label="学校"
            width="180">
          </el-table-column>

          <el-table-column
            prop="collegeName"
            label="学院"
            width="180">
          </el-table-column>

          <el-table-column
            prop="majorName"
            label="专业"
            width="180">
          </el-table-column>

          <el-table-column
            prop="grade"
            label="年级"
            width="100">
          </el-table-column>

          <el-table-column
            prop="classId"
            label="班级"
            width="100">
          </el-table-column>

          <el-table-column
            label="操作"
            fixed="right"
            width="200">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                size="mini"
                type="primary"
                @click="handleViewResults(scope.row)">
                查看测试结果
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>

        <!-- 编辑对话框 -->
        <el-dialog
          title="编辑学生信息"
          :visible.sync="dialogVisible"
          width="50%">
          <el-form
            ref="editForm"
            :model="editForm"
            :rules="rules"
            label-width="100px">
            <el-form-item label="用户号" prop="userId">
              <el-input v-model="editForm.userId" disabled></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="editForm.name"></el-input>
            </el-form-item>
            <el-form-item label="学校" prop="universityName">
              <el-input v-model="editForm.universityName"></el-input>
            </el-form-item>
            <el-form-item label="学院" prop="collegeName">
              <el-input v-model="editForm.collegeName"></el-input>
            </el-form-item>
            <el-form-item label="专业" prop="majorName">
              <el-input v-model="editForm.majorName"></el-input>
            </el-form-item>
            <el-form-item label="年级" prop="grade">
              <el-input v-model="editForm.grade"></el-input>
            </el-form-item>
            <el-form-item label="班级" prop="classId">
              <el-input v-model="editForm.classId"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
          </div>
        </el-dialog>

        <!-- 测试结果对话框 -->
        <el-dialog
          title="测试结果"
          :visible.sync="resultDialogVisible"
          width="70%">
          <div v-if="currentStudent">
            <h3>{{ currentStudent.name }} 的测试结果</h3>
            <el-table
              :data="testResults"
              style="width: 100%">
              <el-table-column
                prop="testTime"
                label="测试时间"
                width="180">
                <template slot-scope="scope">
                  {{ formatDate(scope.row.testTime) }}
                </template>
              </el-table-column>
              <el-table-column
                prop="mbtiType"
                label="MBTI类型"
                width="120">
              </el-table-column>
              
              <!-- 各项得分列 -->
              <el-table-column label="各项得分" width="300">
                <template slot-scope="scope">
                  <div class="score-container">
                    <el-tooltip content="外向(E) vs 内向(I)" placement="top">
                      <div class="score-item">
                        <span>E-I:</span>
                        <span>{{ scope.row.eScore }} - {{ scope.row.iScore }}</span>
                      </div>
                    </el-tooltip>
                    <el-tooltip content="感觉(S) vs 直觉(N)" placement="top">
                      <div class="score-item">
                        <span>S-N:</span>
                        <span>{{ scope.row.sScore }} - {{ scope.row.nScore }}</span>
                      </div>
                    </el-tooltip>
                    <el-tooltip content="思考(T) vs 情感(F)" placement="top">
                      <div class="score-item">
                        <span>T-F:</span>
                        <span>{{ scope.row.tScore }} - {{ scope.row.fScore }}</span>
                      </div>
                    </el-tooltip>
                    <el-tooltip content="判断(J) vs 感知(P)" placement="top">
                      <div class="score-item">
                        <span>J-P:</span>
                        <span>{{ scope.row.jScore }} - {{ scope.row.pScore }}</span>
                      </div>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-dialog>
      </template>
    </el-card>
  </div>
</template>

<script>
import { userApi, testResultApi } from '@/api'

export default {
  name: 'TeacherStudents',
  data() {
    return {
      loading: false,
      saving: false,
      students: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      resultDialogVisible: false,
      currentStudent: null,
      testResults: [],
      filterForm: {
        userId: '',
        name: '',
        grade: '',
        classId: ''
      },
      editForm: {
        userId: '',
        name: '',
        universityName: '',
        collegeName: '',
        majorName: '',
        grade: '',
        classId: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { max: 50, message: '姓名长度不能超过50个字符', trigger: 'blur' }
        ],
        universityName: [
          { required: true, message: '请输入学校名称', trigger: 'blur' }
        ],
        collegeName: [
          { required: true, message: '请输入学院名称', trigger: 'blur' }
        ],
        majorName: [
          { required: true, message: '请输入专业名称', trigger: 'blur' }
        ],
        grade: [
          { required: true, message: '请输入年级', trigger: 'blur' }
        ],
        classId: [
          { required: true, message: '请输入班级', trigger: 'blur' }
        ]
      },
      teacherInfo: {
        grade: '',
        classId: ''
      },
      noClassInfo: false
    }
  },
  created() {
    this.initTeacherInfo()
  },
  methods: {
    formatDate(date) {
      if (!date) return '';
      try {
        return new Date(date).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      } catch (error) {
        console.error('日期格式化错误:', error);
        return date;
      }
    },
    async initTeacherInfo() {
      try {
        const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
        if (!userInfo.userId) {
          this.$message.error('未找到用户信息，请重新登录')
          this.$router.push('/admin/login')
          return
        }
        
        const response = await userApi.getById(userInfo.userId)
        if (response.code === 200 && response.data) {
          if (response.data.grade && response.data.classId) {
            this.teacherInfo.grade = response.data.grade
            this.teacherInfo.classId = response.data.classId
            this.filterForm.grade = response.data.grade
            this.filterForm.classId = response.data.classId
            this.fetchStudents()
          } else {
            this.noClassInfo = true
            this.$message.warning('您还未设置带班信息，请先在个人中心设置带班信息')
          }
        } else {
          throw new Error(response.message || '获取用户信息失败')
        }
      } catch (error) {
        console.error('获取教师信息失败：', error)
        this.$message.error(error.message || '获取教师信息失败')
        this.noClassInfo = true
      }
    },
    async fetchStudents() {
      try {
        this.loading = true
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          ...this.filterForm,
          role: 'student'  // 只查询学生角色
        }
        const response = await userApi.list(params)
        this.students = response.data.list
        this.total = response.data.total
      } catch (error) {
        console.error('获取学生列表失败：', error)
        this.$message.error('获取学生列表失败')
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchStudents()
    },
    resetFilter() {
      this.filterForm.userId = ''
      this.filterForm.name = ''
      // 保持年级和班级不变
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchStudents()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchStudents()
    },
    handleEdit(row) {
      this.editForm = { ...row }
      this.dialogVisible = true
    },
    async handleSave() {
      try {
        await this.$refs.editForm.validate()
        this.saving = true
        
        const res = await userApi.update(this.editForm.userId, this.editForm)
        if (res.code === 200) {
          this.$message.success('更新成功')
          this.dialogVisible = false
          this.fetchStudents()
        } else {
          this.$message.error(res.msg || '更新失败')
        }
      } catch (error) {
        console.error('更新学生信息错误：', error)
        this.$message.error(error.response?.data?.msg || '更新失败，请检查输入信息')
      } finally {
        this.saving = false
      }
    },
    async handleViewResults(row) {
      try {
        this.currentStudent = row
        const res = await testResultApi.getByUserId(row.userId)
        if (res.code === 200) {
          this.testResults = this.processResults(res.data)
          this.resultDialogVisible = true
        } else {
          this.$message.error('获取测试结果失败')
        }
      } catch (error) {
        console.error('获取测试结果错误：', error)
        this.$message.error('获取测试结果失败')
      }
    },
    
    // 处理测试结果数据
    processResults(data) {
      if (!data || !Array.isArray(data)) return []
      
      return data.map(item => {
        const result = { ...item }
        
        // 处理测试时间字段
        if (item.test_time && !item.testTime) {
          result.testTime = item.test_time
        }
        
        // 确保分数字段为数字类型，但保留原始值，不再应用Math.max(1)
        const scoreFields = [
          'eScore', 'iScore', 'sScore', 'nScore', 
          'tScore', 'fScore', 'jScore', 'pScore'
        ]
        
        // 检查驼峰命名和下划线命名两种情况
        scoreFields.forEach(field => {
          // 处理驼峰命名字段 (如 eScore)
          if (result[field] !== undefined) {
            result[field] = Number(result[field])
          }
          
          // 处理下划线命名字段 (如 escore)
          const snakeField = field.replace(/([A-Z])/g, c => '_' + c.toLowerCase())
          if (result[snakeField] !== undefined && result[field] === undefined) {
            result[field] = Number(result[snakeField])
          }
        })
        
        return result
      })
    }
  }
}
</script>

<style scoped>
.students-container {
  padding: 20px;
}

.students-card {
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.description-text {
  display: inline-block;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

h3 {
  margin: 0 0 20px 0;
  color: #303133;
}

.no-class-info {
  text-align: center;
  padding: 20px;
}

.no-class-info .el-alert {
  display: inline-block;
  min-width: 400px;
}

.class-info {
  margin-bottom: 20px;
}

/* 得分显示样式 */
.score-container {
  display: flex;
  flex-direction: column;
}

.score-item {
  margin: 2px 0;
  font-size: 13px;
  display: flex;
  justify-content: space-between;
  background-color: #f5f7fa;
  padding: 3px 8px;
  border-radius: 3px;
  transition: background-color 0.3s;
}

.score-item:hover {
  background-color: #edf2fc;
}
</style> 